package com.qingxin.repertory.service;
import java.math.BigDecimal;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qingxin.repertory.entity.Repertory;
import com.qingxin.repertory.entity.RepertoryAccount;
import com.qingxin.sys.dao.Querier;
import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.mvc.PageParam;
import com.qingxin.sys.mvc.Pager;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.service.BaseService;

@Service
public class RepertoryAccountService extends BaseService<RepertoryAccount, String>{
	@Autowired
	private RepertoryService repertoryService;
	/**
	 * 流水账数据
	 * @param repertoryid
	 * @param pageParam
	 * @param request
	 * @return
	 */
	public Pager list(String repertoryid,PageParam pageParam, HttpServletRequest request){
		Querier querier = Querier.create("from RepertoryAccount where repertoryid=:repertoryid order by createTime asc");
		querier.setParam("repertoryid",repertoryid);
		Pager pager = pageByQuerier(querier, pageParam);
		return pager;
	}
	
	/**
	 * 保存库存数据
	 * @param repertory
	 * @param parkid
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError add(RepertoryAccount account,String repertoryid, LoginUser loginUser, HttpServletRequest request){
		Repertory repertory = repertoryService.get(repertoryid);
		BigDecimal amount = repertory.getAmount();//总
		BigDecimal repertory_num = repertory.getRepertory_num();//剩余
		BigDecimal used_num = repertory.getUsed_num();//已使用
		BigDecimal addNum = null;
		BigDecimal goNum = null;
		BigDecimal backNum = null;
		
		if(account.getType().equals("0")){
			addNum = account.getNumber();
			amount = amount.add(addNum);
			repertory_num = repertory_num.add(addNum);
		}
		else if(account.getType().equals("1")){
			goNum = account.getNumber();
			if(goNum.compareTo(repertory_num) == 1){
				return  new SysError("发放数量不能大于库存数量");
			}
			repertory_num = repertory_num.subtract(goNum);
			used_num = used_num.add(goNum);
		}
		else if(account.getType().equals("2")){
			backNum = account.getNumber();
			if(backNum.compareTo(used_num) == 1){
				return  new SysError("回收数量不能大于已使用数量");
			}
			repertory_num = repertory_num.add(backNum);
			used_num = used_num.subtract(backNum);
		}
		
		repertory.setAmount(amount);
		repertory.setRepertory_num(repertory_num);
		repertory.setUsed_num(used_num);
		repertoryService.update(repertory,loginUser, request);
		Date now = new Date();
		account.setCreateTime(now);
		account.setCreateBy(loginUser.getLogin_name());
		this.save(account);
		return null;
	}
	
}
